package com.share;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
	private static MessageDigest messageDigest;
	private static String result = "";
	private static byte[] args = null;

	public static String getMD5String(String userpass) throws RuntimeException{
		try {
			// 生成MessageDigest对象,传入所用算法的参数(MD5)
			messageDigest = MessageDigest.getInstance("MD5");
			// 使用 getBytes( )方法生成字符串数组
			messageDigest.update(userpass.getBytes("GBK"));
			// 执行MessageDigest对象的digest( )方法完成计算，计算的结果通过字节类型的数组返回
			args = messageDigest.digest();
		} catch (NoSuchAlgorithmException exception) {
			exception.printStackTrace();
			throw new RuntimeException(exception);
		} catch (UnsupportedEncodingException exception) {
			exception.printStackTrace();
			throw new RuntimeException(exception);
		} finally {
			messageDigest.reset();
		}

		// 将结果转换成字符串
		result = "";// result清空，否则它会自动累加！！！
		for (int i = 0; i < args.length; i++) {
			result += Integer.toHexString((0x000000ff & args[i]) | 0xffffff00)
					.substring(6);
		}
		return result;
	}
}
